
var app = getApp();

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}





/**
 * 甜果果微信的的request
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Nideshop-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log("success");

        if (res.statusCode == 200) {

          if (res.data.errno == 401) {
            //需要登录后才可以操作

            let code = null;
            return login().then((res) => {
              code = res.code;
              return getUserInfo();
            }).then((userInfo) => {
              //登录远程服务器
              request(api.AuthLoginByWeixin, { code: code, userInfo: userInfo }, 'POST').then(res => {
                if (res.errno === 0) {
                  //存储用户信息
                  wx.setStorageSync('userInfo', res.data.userInfo);
                  wx.setStorageSync('token', res.data.token);
                  
                  resolve(res);
                } else {
                  reject(res);
                }
              }).catch((err) => {
                reject(err);
              });
            }).catch((err) => {
              reject(err);
            })
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: function (err) {
        reject(err)
        console.log("failed")
      }
    })
  });
}

/**
 * 检查微信会话是否过期
 */
function checkSession() {
  return new Promise(function (resolve, reject) {
    wx.checkSession({
      success: function () {
        resolve(true);
      },
      fail: function () {
        reject(false);
      }
    })
  });
}

/**
 * 调用微信登录
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.login({
      success: function (res) {
        if (res.code) {
          //登录远程服务器
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

function getUserInfo() {
  return new Promise(function (resolve, reject) {
    wx.getUserInfo({
      withCredentials: true,
      success: function (res) {
        resolve(res);
      },
      fail: function (err) {
        reject(err);
      }
    })
  });
}

function redirect(url) {

  //判断页面是否需要登录
  if (false) {
    wx.redirectTo({
      url: '/pages/auth/login/login'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/static/images/icon_error.png'
  })
}

//当前时间加20天
function getdeadline(days){
  //获取当前时间戳  
  var timestamp = Date.parse(new Date());  
  timestamp = timestamp / 1000;  
  console.log("当前时间戳为：" + timestamp);
  //加一天的时间戳：  
  var tomorrow_timetamp = timestamp + 24 * 60 * 60  *days;  
  //加一天的时间：  
  var n_to = tomorrow_timetamp * 1000;  
  var tomorrow_date = new Date(n_to);  
  return  tomorrow_date
}
// function formatNumber(n) {
//   n = n.toString()
//   return n[1] ? n : '0' + n
// }
/** 
 * 时间戳转化为年 月 日 时 分 秒 
 * number: 传入时间戳 
 * format：返回格式，支持自定义，但参数必须与formateArr里保持一致 
*/
function formatTimeTwo(number, format) {

  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];

  var date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
}
function stringToDate(dateStr){

      //若月份、日期、小时、分钟、秒未满10的情况，取整时祛除下前面的0(如04转为4)，否则取整会失败。
  
      let fullYear = parseInt(dateStr.substring(0,4));
  
      let month = parseInt(dateStr.substring(5, 7).substring(0, 1) == '0' ? dateStr.substring(6, 7) : dateStr.substring(5, 7));
  
      let day = parseInt(dateStr.substring(8, 10).substring(0, 1) == '0' ? dateStr.substring(9, 10) : dateStr.substring(8, 10));
  
      let hour = parseInt(dateStr.substring(11, 13).substring(0, 1) == '0' ? dateStr.substring(12, 13) : dateStr.substring(11, 13));
  
      let minute = parseInt(dateStr.substring(14, 16).substring(0, 1) == '0' ? dateStr.substring(15, 16) : dateStr.substring(14, 16));
  
      let second = parseInt(dateStr.substring(17, 19).substring(0, 1) == '0' ? dateStr.substring(18, 19) : dateStr.substring(17, 19));
  
      return new Date(fullYear,month-1,day,hour,minute,second);
  
    }
  
module.exports = {
  formatTime: formatTime,
  request,
  redirect,
  showErrorToast,
  checkSession,
  login,
  getUserInfo,
  //formatTimeTwo: formatTimeTwo,
  getdeadline:getdeadline,
  stringToDate:stringToDate,
}

